# -- coding cp949 --
#-*- encoding: utf-8 -*-
from PyQt4 import QtCore , QtGui , uic
from lib.customUI import customUI
from lib.papyDBTable import *
from lib.itemModel import treeItem, PSSdata
from lib import globalVar as GV
import os

#PSSdata = PSSdata( prjID=4 , prjName ='mini' , seqID=38 , seqName = 'Attempt' , shotID=186 , shotName = 'sh078')
PSSdata = PSSdata( prjID=1 , prjName ='Phantom' , seqID=1 , seqName = 'frist' , shotID=1 , shotName = 'sh202')
        
class taskDelegate(QtGui.QStyledItemDelegate):    
    def __init__(self , parent = None ):
        super(taskDelegate ,self ).__init__( parent )
        self.parent = parent
      
    def createEditor(self, parent, option, index):  
        ## ////////////////////////////////////////// 테이블 틀 만들기     
        dept = [ 'Animation' , 'FX' , 'Layout' , 'Lighting' , 'Render']        
        if index.column() == 0 :
            deptID = DEPARTMENT.search( 'deptID' ,  deptName=dept[ index.row() ] )
            ver_cb = QtGui.QComboBox( parent )
            ver_cb.setFont(  QtGui.QFont('Arial',9) )
            theList = USER_INFO.search('userName' , deptID = deptID)             
            if type( theList ) == type(u'') :
                theList = [ theList ]   
            if theList != None :
                map(lambda x:ver_cb.addItem(  x  ) , theList )
            return ver_cb           
        elif index.column() == 1:
            status = ['Ready','WIP','Final','Hold']
            status_cb = QtGui.QComboBox( parent )
            status_cb.addItems( status )
            return status_cb      
        elif index.column() == 2  or index.column() == 3:
            cal = QtGui.QDateEdit(parent)
            cal.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
            cal.setDisplayFormat( QtCore.QString("yyyy-MM-dd") )
            cal.setCalendarPopup( True )
            cal.setDate( QtCore.QDate.currentDate() )                 
            return cal
        elif index.column() == 4:
            editor = QtGui.QLineEdit( parent )
            return editor  
                                    
    def setModelData(self, editor, model, index):    
        ## ////////////////////////////////////////// 테이블 칸 데이터 타입 설정         
        if index.column() == 0 or index.column() == 1:
            model.setData(index, QtCore.QVariant(editor.currentText())) 
        elif index.column() == 2 or index.column() == 3:            
            date = editor.date()
            pdate = str(date.year()) +"-"+ str(date.month()) +"-"+ str(date.day()) 
            pdate = papyDB.refineDate( str(pdate) )
            model.setData(index, QtCore.QVariant( pdate ))
        elif index.column() == 4:
            model.setData(index, QtCore.QVariant(editor.text()))


    def setEditorData(self, editor, index):        
        if index.column() == 0 or index.column() == 1: 
            text = index.model().data(index, QtCore.Qt.DisplayRole).toString()
            i = editor.findText(text)
            if i == -1:
                i = 0
            editor.setCurrentIndex(i)
        elif index.column() == 2 or index.column() == 3:
#             text = editor.selectedDate()
#            editor.setText( str(date.year()) +"-"+ str(date.month()) +"-"+ str(date.day())  )
#            i = editor.findText(text)
#            if i == -1:
#                i = 0
#            editor.setCurrentIndex(i) 
            pass


class taskBoard(QtGui.QWidget):
    def __init__(self , parent = None ):
        QtGui.QWidget.__init__(self , parent)
        self.taskBoard_widget = uic.loadUi( r'ui/dashBoard_task_widget.ui' , self )
        self.refreshBoard(PSSdata)        
        self.taskBoard_widget.label.setText("")        
        self.shot_table.setItemDelegate( taskDelegate(self) )
        self.taskBoard_widget.edit_btn.clicked.connect( self.editData )

        
    def editData( self ):    
        self.refineData(  )        
#        print "===========================================INSERT or MODIFY===========================================" 
    
            
    def refineData(self):
        ## ////////////////////////////////////////// 입력,수정한 데이터 정리 후 register,update
#        print "refine", self.finPSS
        self.shotName = self.finPSS['shotName']
        shotID = self.finPSS['shotID']
#        print shotName, shotID, type(shotID)        
        for x in range(5):
            self.returnDeptNo = x
            if self.shot_table.item(x,0) != None and self.shot_table.item(x,1) != None and self.shot_table.item(x,2) != None and self.shot_table.item(x,3) != None:
                new0 = self.shot_table.item(x,0).text()
                userID = int( papyDB.getID("USER_INFO", "userID", "userName", new0) )
#                if GV.testUserID == '': userID = int( papyDB.getID("USER_INFO", "userID", "userName", new0) )
#                else :                  userID = int( GV.testUserID )
                new1 = str ( self.shot_table.item(x,1).text() )
                new2 = str ( self.shot_table.item(x,2).text() ) 
                new3 = str ( self.shot_table.item(x,3).text() ) 
                if self.shot_table.item(x,4) != None : new4 = str ( self.shot_table.item(x,4).text() )
                else : new4 = '' 
                
                deptID = USER_INFO.searches( "deptID" , userID = userID )
                
#                if x != 4 : 
                jobInfo = JOB_INFO.searches( "ID" , shotID=self.finPSS['shotID'] , userID=userID )
#                else : 
#                    jobInfo = RENDER.searches("ID" , shotID=self.finPSS['shotID'] , userID=userID )                    
#                print "\n", "[ARTIST NAME]", new0, "[ID]", userID, "\n", "[STATUS]", new1, "[S DATE]", new2, "[E DATE]", new3, "[DESC]", new4 
#                print "jobInfo", jobInfo
                
                dic = {'status':new1 , 'startDate':new2 , 'endDate':new3 , 'description':new4 , 'shotID':shotID , 'userID':userID , 'deptID':deptID}
                if jobInfo == [] :
#                    if x != 4:
                    papyDB.query( """
                      INSERT INTO JOB_INFO(status,startDate,endDate,description,shotID,userID,deptID) 
                      VALUES('%(status)s','%(startDate)s','%(endDate)s','%(description)s','%(shotID)s','%(userID)s','%(deptID)s')""" % dic ) 
#                    else : 
#                        papyDB.query( """
#                          INSERT INTO RENDER(status,startDate,endDate,description,shotID,userID) 
#                          VALUES('%(status)s','%(startDate)s','%(endDate)s','%(description)s','%(shotID)s','%(userID)s')""" % dic ) 
#                    fID = papyDB.getLastID('JOB_INFO' , 'ID')
#                    papyDB.regTable('JOB_VERSION', 1, fID)
#                    JOB_VERSION.register(ver='1' , fID=fID)
#                    self.saveFile()
#                    print "==========================================REGISTER"
                else:
#                    if x != 4 :
                    JOB_INFO.update('status', new1, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
                    JOB_INFO.update('startDate', new2, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
                    JOB_INFO.update('endDate', new3, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
                    if new1 == 'Final' :
                        todayDate = papyDB.getTodayDate()
                        JOB_INFO.update('finalDate', todayDate, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])    
                    JOB_INFO.update('description', new4, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
                    JOB_INFO.update('userID', userID, ID=jobInfo)
#                        JOB_INFO.update('userID', userID, ID=jobInfo, shotID=self.finPSS['shotID'])
#                    else :
#                        RENDER.update('status', new1, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
#                        RENDER.update('startDate', new2, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
#                        RENDER.update('endDate', new3, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
#                        if new1 == 'Final' :
#                            todayDate = papyDB.getTodayDate()
#                            RENDER.update('finalDate', todayDate, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])    
#                        RENDER.update('description', new4, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
#                        RENDER.update('userID', userID, ID=jobInfo)
##                        RENDER.update('userID', userID, ID=jobInfo, userID=userID, shotID=self.finPSS['shotID'])
#                    print "==========================================UPDATE"    
        self.refreshBoard( self.finPSS ) 
        
        
#    def saveFile(self):
#        prjCode = PSSdata['prjName']
#        deptInfo = []
#        if self.returnDeptNo == 0:
#            deptInfo = ['Anim' , 'anim']
#            print "Anim"
#        elif self.returnDeptNo == 1:
#            deptInfo = ['FX' , 'FX']
#        elif self.returnDeptNo == 2:
#            deptInfo = ['layout' , 'layout']
#            print "Layout"
##        elif self.returnDeptNo == 3:
##            deptInfo = ['Lighting' , 'light']
##            print "Light"
##        elif self.returnDeptNo == 4:
##            deptInfo = ['Render' , 'ren']
##            print "Render"
#            
#        
#        s = '"\\\"'
#        ######################################################################## ????????????????????????????????????????????????????????????????
#        firstFile = ''
#        ######################################################################## ????????????????????????????????????????????????????????????????
#        filePath = GV.PROJECT_SERVER + s[1] + prjCode + s[1] + "Dev" + s[1] + deptInfo[0] + s[1] + self.shotName+'_'+deptInfo[1]+'_001.ma'
#        print filePath
#        os.system("copy %s %s" % (firstFile , filePath) )
        
                     
             
    def jobInfoSearch( self , dept ):
        return JOB_INFO.searches('userID' , 'status' , 'startDate' , 'endDate' , 'desCription' , shotID = PSSdata['shotID'] , deptID=dept) 
        
            
    def refreshBoard(self , PSSdata):
#        print "\n\n"
#        print "refresh", PSSdata
        self.finPSS = PSSdata
#        print "refresh", self.finPSS
        ## ////////////////////////////////////////// 테이블에 data 불러오기!
        self.taskBoard_widget.label.setText(PSSdata['shotName'])
        self.shot_table.clearContents()
        self.row = -1
        userID = JOB_INFO.searches("userID" , shotID=PSSdata['shotID'] )
        if type(userID) == type(5) :
            tempID = userID
            userID = []
            userID.append(tempID)  
        for x in range(len(userID)) :
#            userDept = USER_INFO.searches("deptID", userID = userID[x] )
#            print "userDept", userDept
#            if "3" or "6" or "7" in userDept :
            userName = USER_INFO.searches("userName", userID = userID[x] )[0]
            jobArtist = QtGui.QTableWidgetItem()
            jobArtist.setText(userName)
            status = str(JOB_INFO.searches( "status" , userID=userID[x] , shotID=PSSdata['shotID'] )[0])
            jobStatus = QtGui.QTableWidgetItem()
            jobStatus.setText(status)
            startDate = str(JOB_INFO.searches( "startDate" , userID=userID[x] , shotID=PSSdata['shotID'] )[0])
            jobStartDate = QtGui.QTableWidgetItem()
            jobStartDate.setText(startDate)
            endDate = str(JOB_INFO.searches( "endDate" , userID=userID[x] , shotID=PSSdata['shotID'] )[0])
            jobEndDate = QtGui.QTableWidgetItem()
            jobEndDate.setText(endDate)
            desc = str(JOB_INFO.searches( "description" , userID=userID[x] , shotID=PSSdata['shotID'] )[0])    
            jobDesc = QtGui.QTableWidgetItem()
            jobDesc.setText(desc)
            if USER_INFO.searches( "deptID" , userID = userID[x] ) == 3: 
                self.row = 0      
            elif USER_INFO.searches( "deptID" , userID = userID[x] ) == 7:
                self.row = 1
            elif USER_INFO.searches( "deptID" , userID = userID[x] ) == 10:
                self.row = 2
            elif USER_INFO.searches( "deptID" , userID = userID[x] ) == 9:
                self.row = 3
            elif USER_INFO.searches( "deptID" , userID = userID[x] ) == 6:
                self.row = 4
            self.shot_table.setItem( self.row , 0 , jobArtist )
            self.shot_table.setItem( self.row , 1 , jobStatus )
            self.shot_table.setItem( self.row , 2 , jobStartDate )
            self.shot_table.setItem( self.row , 3 , jobEndDate )
            self.shot_table.setItem( self.row , 4 , jobDesc ) 
#        print "==============>> RE-LOAD"
        return self.finPSS
        
        
        
        
        
        
        
        
        
        

        
           
    def setWidgetItem( self , row , itemData ):
        if not itemData : return
#        print 'itemData : ',itemData
#        print 'USER_INFO.searches( "userName" , userID =itemData[0] ) : ' , USER_INFO.searches( "userName" , userID =itemData[0] )
        itemData[0] = USER_INFO.searches( "userName" , userID =itemData[0] )[0] 
        
        theItem = [ QtGui.QTableWidgetItem().setText( x ) for x in itemData ]
#################################################################################################        
#        print theItem
        map( lambda m : self.shot_table.setItem( row , m , theItem[m] ) , range(5) )  
        
        
        
        
if __name__ == '__main__':
    import sys    
    app = QtGui.QApplication(sys.argv)
    ui = taskBoard()       
    ui.taskBoard_widget.show()
#    ui.refreshBoard( PSSdata )
    app.exec_()  
    
    
    